package com.cupdata.zicon.jdk7concurrent.chapter1;



import java.util.Date;
import java.util.concurrent.TimeUnit;



/**
 * In some situations, we will have to wait for the finalization of a thread. For example, we may
have a program that will begin initializing the resources it needs before proceeding with the
rest of the execution. We can run the initialization tasks as threads and wait for its finalization
before continuing with the rest of the program.
For this purpose, we can use the join() method of the Thread class. When we call this
method using a thread object, it suspends the execution of the calling thread until the object
called finishes its execution.


When you run this program, you can see how both Thread objects start their
execution. First, the DataSourcesLoader thread finishes its execution. Then, the
NetworkConnectionsLoader class finishes its execution and, at that moment, the
main Thread object continues its execution and writes the final message.
 * @author SunYabing
 *
 */
public class JoinTest {

	//@Test
	public static void  main(String[] args) throws InterruptedException {
		DataSourcesLoader dsLoader = new DataSourcesLoader();
		Thread thread1 = new Thread(dsLoader,"DataSourcesLoader");
		
		NetworkConnectionsLoader ncLoader = new NetworkConnectionsLoader();
		Thread thread2 = new Thread(ncLoader,"NetworkConnectionLoader");
		
		
		
		thread1.start();
		thread2.start();
		
		
		
		try {
			thread1.join();
			thread2.join();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		System.out.printf("Main: Configuration has been loaded:	%s\n",new Date());
		Thread.currentThread().sleep(6);
		
//		thread1.interrupt();
//		thread2.interrupt();
	}

}

class DataSourcesLoader implements Runnable {

	@Override
	public void run() {
		System.out.printf("DataSourcesLoader Beginning data sources loading: %s\n", new Date());
		try {
			TimeUnit.SECONDS.sleep(4);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		System.out.printf("DataSourcesLoader Data sources loading has finished: " + "%s\n",
				new Date());
	}

}


class NetworkConnectionsLoader implements Runnable {

	@Override
	public void run() {
		System.out.printf("NetworkConnectionsLoader Beginning data sources loading: %s\n", new Date());
		try {
			TimeUnit.SECONDS.sleep(6);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		System.out.printf("NetworkConnectionsLoader Data sources loading has finished: " + "%s\n",
				new Date());
	}

}




